package azalea.mqtt.gui;

import java.io.*;

public class SerializationUtils {
    
    /**
     * 序列化对象到文件
     * @param obj 要序列化的对象
     * @param filePath 文件路径
     */
    public static void serializeToFile(Object obj, String filePath) {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath))) {
            oos.writeObject(obj);
            System.out.println("对象已序列化到文件: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 从文件反序列化对象
     * @param filePath 文件路径
     * @return 反序列化后的对象
     */
    public static Object deserializeFromFile(String filePath) {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath))) {
            Object obj = ois.readObject();
            System.out.println("从文件 " + filePath + " 反序列化对象成功");
            return obj;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 序列化对象到字节数组
     * @param obj 要序列化的对象
     * @return 字节数组
     */
    public static byte[] serializeToBytes(Object obj) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            oos.flush();
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从字节数组反序列化对象
     * @param bytes 字节数组
     * @return 反序列化后的对象
     */
    public static Object deserializeFromBytes(byte[] bytes) {
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis)) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}